#include "Linkedlist.h"
#include <iostream>
using namespace std;

void add_poly(LinkedList<int> *list1, LinkedList<int> *list2, LinkedList<int> *result)
{
    Node<int> *current1 = list1->head;
    Node<int> *current2 = list2->head;

    while (current1 != NULL && current2 != NULL)
    {
        if (current1->mi == current2->mi)
        {
            if (current1->num + current2->num != 0)
            {
                result->push(current1->num + current2->num, current1->mi);
                current1 = current1->next;
                current2 = current2->next;
            }
            else
            {
                current1 = current1->next;
                current2 = current2->next;
            }
        }
        else if (current1->mi < current2->mi)
        {
            result->push(current1->num, current1->mi);
            current1 = current1->next;
        }
        else if (current2->mi < current1->mi)
        {
            result->push(current2->num, current2->mi);
            current2 = current2->next;
        }
    }
    while (current1 != NULL)
    {
        result->push(current1->num, current1->mi);
        current1 = current1->next;
    }
    while (current2 != NULL)
    {
        result->push(current2->num, current2->mi);
        current2 = current2->next;
    }
}

int main()
{
    int size1, size2;
    cin >> size1;
    LinkedList<int> *list1 = new LinkedList<int>;
    LinkedList<int> *list2 = new LinkedList<int>;
    LinkedList<int> *list_re = new LinkedList<int>;
    for (int i = 0; i < size1; i++)
    {
        int num, mi = 0;
        cin >> num >> mi;
        list1->push(num, mi);
    }

    cin >> size2;
    for (int i = 0; i < size2; i++)
    {
        int num, mi = 0;
        cin >> num >> mi;
        list2->push(num, mi);
    }

    add_poly(list1, list2, list_re);

    cout << list_re->size << endl;
    list_re->Print();
    return 0;
}